package com.sdry.web.controller.lz;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sdry.mapper.llm.CancellingStockDetailMapper;
import com.sdry.model.lz.AbnormalAdjustment;
import com.sdry.model.lz.AbnormalDetail;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.OutStockOrder;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.lz.AbnormalAdjustmentService;
import com.sdry.utils.ResponseUtil;

/**
 * @ClassName AbnormalAdjustmentController
 * @Description 异常调整
 * @Author lz
 * @Date 2019年4月23日 10:59:22
 * @Version 1.0
 */
@Controller
@RequestMapping("/abnormalAdjustment")
public class AbnormalAdjustmentController {
	public static final Integer AFFECT_ROW = 0;
	
	@Resource
	AbnormalAdjustmentService abnormalAdjustmentService;
	
	@Resource
	CancellingStockDetailMapper cancellingStockDetailMapper;
	
	@Resource
	CancellingStockDetailService cancellingStockDetailService;
	/**
	 * 新增异常调整
	 * @param response
	 * @param order
	 */
	@RequestMapping("/addAbnormalAdjustment")
	public void addAbnormalAdjustment(HttpServletResponse response, AbnormalAdjustment abnormalAdjustment){
		abnormalAdjustment.setRemark("0");
		Long affectRow = abnormalAdjustmentService.addAbnormalAdjustment(abnormalAdjustment);
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新增异常调整
	 * @param response
	 * @param order
	 */
	@RequestMapping("/addAbnormalDetail")
	public void addAbnormal(HttpServletResponse response, AbnormalDetail  abnormalDetail){
		
		Long affectRow = abnormalAdjustmentService.addAbnormalDetail(abnormalDetail);
		try {
			ResponseUtil.write(response, affectRow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
 	 * 根据ID删除该行数据
 	 * @param response
 	 * @param idArr
 	 */
 	@RequestMapping("/deleteAbnormalAdjustmentById")
	public void deleteAbnormalAdjustmentById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
 		if(idArr.length > 0){
 			for (int i = 0; i < idArr.length; i++) {
 	            Long affectRow = abnormalAdjustmentService.deleteAbnormalAdjustmentById(Long.parseLong(idArr[i]));
 	            if (affectRow > AFFECT_ROW) {
 	                try {
						ResponseUtil.write(response, affectRow);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            } else {
 	                try {
						ResponseUtil.write(response, AFFECT_ROW);
					} catch (Exception e) {
						e.printStackTrace();
					}
 	            }
 	        }
 		}
	}
 	/**
	 * 减物料良品库的库存
	 * @param materielId 物料ID
	 * @param materielQuantity	物料数量
	 */
	public void inventoryReduction(Long materielId, Integer materielQuantity) {
		//根据物料ID查良品库的库存
		List<ZcInventoryInfoEntity> list = cancellingStockDetailService.getInventoryByMid(materielId);
		//遍历减库存（1个物料ID多条库存记录，减后为0的，删除该记录）
		/*for(ZcInventoryInfoEntity info : list){*/
		for(int i = 0; i < list.size(); i++) {
			//System.out.println("补发数量="+materielQuantity+":  库存数量="+info.getmNum());
			materielQuantity = materielQuantity - list.get(i).getSmallNum();
			//如果物料数量大于库存
			if(materielQuantity > 0){
				//删除这条数据
				//cancellingStockDetailService.deleteInventoryById(info.getId());
				int materielQuantity1;
				materielQuantity1= list.get(i).getBigNum() - materielQuantity ;
				if(materielQuantity1 > 0) {
					//修改库存数量
					Map<String, Object> map = new HashMap<>();
					map.put("id", list.get(i).getId());
					map.put("fieldName", "mNum");
					map.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map);
					Map<String, Object> map1 = new HashMap<>();
					map1.put("id", list.get(i).getId());
					map1.put("fieldName", "bigNum");
					map1.put("fieldValue", Math.abs(materielQuantity1));
					cancellingStockDetailService.updateInventory(map1);
					Map<String, Object> map2 = new HashMap<>();
					map2.put("id", list.get(i).getId());
					map2.put("fieldName", "smallNum");
					map2.put("fieldValue", 0);
					cancellingStockDetailService.updateInventory(map2);
					break;
				} else {
					//删除这条数据
					cancellingStockDetailService.deleteInventoryById(list.get(i).getId());
					//求绝对值
					inventoryReduction(list.get(i).getMid(), Math.abs(materielQuantity1));
				}
			} else {
				//修改库存数量
				Map<String, Object> map = new HashMap<>();
				map.put("id", list.get(i).getId());
				map.put("fieldName", "smallNum");
				map.put("fieldValue", Math.abs(materielQuantity));
				cancellingStockDetailService.updateInventory(map);
				Map<String, Object> map1 = new HashMap<>();
				map1.put("id", list.get(i).getId());
				map1.put("fieldName", "mNum");
				map1.put("fieldValue", Math.abs(materielQuantity)+list.get(i).getBigNum());
				cancellingStockDetailService.updateInventory(map1);
			}
			return;
		}
	}
 	/**
 	 * 行内编辑订单表
 	 * @param response
 	 * @param id 订单ID
 	 * @param fieldName 修改的字段名称
 	 * @param fieldValue 修改的字段的值
 	 */
 	@RequestMapping("/updateAbnormalAdjustmentById")
	public void updateAbnormalAdjustmentById(HttpServletResponse response, String id, String fieldName, String fieldValue){
		Long affectRow = abnormalAdjustmentService.updateAbnormalAdjustmentById(id, fieldName, fieldValue);
		
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
 	@RequestMapping("/updateAbnormaldetailById")
	public void updateAbnormalById(HttpServletResponse response, String id, String fieldName, String fieldValue){
		Long affectRow = abnormalAdjustmentService.updateAbnormalDetailById(id, fieldName, fieldValue);
		
		AbnormalDetail abnormalDetail=abnormalAdjustmentService.queryAbnormalDetailByid(Long.parseLong(id));
		inventoryReduction(abnormalDetail.getMid(), Integer.parseInt(fieldValue));
		if(affectRow > AFFECT_ROW){
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

 	/**
	 * 分页条件查询异常调整
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryAbnormalAdjustmentCriteria")
	public void queryAbnormalAdjustmentCriteria(HttpServletResponse response, LzQueryCriteria criteria){
		String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        //String keyword03 = criteria.getKeyword03();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        /*if(keyword03 == null){
            keyword03 = "";
        }*/
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
		//criteria.setKeyword03(keyword03);
        List<AbnormalAdjustment> abnormalAdjustmentList = abnormalAdjustmentService.queryAbnormalAdjustmentCriteria(criteria);
        int count = abnormalAdjustmentService.countAbnormalAdjustmentCriteria(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(abnormalAdjustmentList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
     * 根据出库单号查询出库单
     * @param response
     * @throws Exception
     */
 	@RequestMapping("/queryOutStockOrderByNum")
	public void queryCustomerByName(HttpServletResponse response, String out_order_num) throws Exception{
		List<OutStockOrder> outStockOrderList = abnormalAdjustmentService.queryOutStockOrderByNum(out_order_num);
		JSONArray jsonArray = JSONArray.fromObject(outStockOrderList);
		if (outStockOrderList.size() > 0) {
            ResponseUtil.write(response, jsonArray);
        } else {
            ResponseUtil.write(response, null);
        }
	}
   
  	@RequestMapping("/queryMateriel")
 	public void queryMateriel(HttpServletResponse response, String cid) throws Exception{
 		List<Materiel> materiels = abnormalAdjustmentService.queryMaCuRe(Long.parseLong(cid));
 		 JSONObject jsonObject = new JSONObject();
         JSONArray jsonArray = JSONArray.fromObject(materiels);
         jsonObject.put("code", AFFECT_ROW);
         jsonObject.put("data", jsonArray);
      
         try {
             ResponseUtil.write(response, jsonObject);
         } catch (Exception e) {
             e.printStackTrace();
         }
 	}
  	
  	
	@RequestMapping("/queryAbnormalDetail")
 	public void queryAbnormalDetail(HttpServletResponse response, String aid) throws Exception{
 		List<Materiel> materiels = abnormalAdjustmentService.queryAbnormalDetail(Long.parseLong(aid));
 		for (Materiel materiel : materiels) {
 			Map<String, Object> map = new HashMap<>();
			map.put("mid", materiel.getMid());
 			List<ZcInventoryInfoEntity> infoEntity = cancellingStockDetailMapper.getQuantityByMid(map);
			long sum=0;
			for (ZcInventoryInfoEntity zcInventoryInfoEntity : infoEntity) {
				sum+=zcInventoryInfoEntity.getmNum();
			}
			String k=Long.toString(sum); 
			materiel.setKnum(k);
			
		}
 		
 		 JSONObject jsonObject = new JSONObject();
         JSONArray jsonArray = JSONArray.fromObject(materiels);
         jsonObject.put("code", AFFECT_ROW);
         jsonObject.put("data", jsonArray);
      
         try {
             ResponseUtil.write(response, jsonObject);
         } catch (Exception e) {
             e.printStackTrace();
         }
 	}
}

